package com.st.warehouse.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import com.st.warehouse.BuildConfig;
import com.st.warehouse.R;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class SystemUtils {
    final public static String photoDir = Environment.getExternalStorageDirectory() + "/DCIM/Camera/";// 拍照路径
    private final static String TAG = "SystemUtil";
    final static String photoCacheTime = String.valueOf(System.currentTimeMillis() / (2 * 24 * 60 * 60 * 1000)); // 图片磁盘缓存时间，超过2天自动清空
    private static AlertDialog alertDialog;     // 弹窗


    /**
     * 弹框复制文本-文本下面位置
     * @param context 上下文
     * @param anchorView 被复制文本视图
     * @param textToCopy 被复制的文本内容
     */
    public static void showCopyPopupWindow(final Context context, final View anchorView, final String textToCopy) {
        // 创建 PopupWindow
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popupView = inflater.inflate(R.layout.layout_popup_window, null);
        Button copyButton = popupView.findViewById(R.id.btn_copy);
        final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 设置按钮点击事件
        copyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取剪贴板管理器
                ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建 ClipData 对象
                ClipData clipData = ClipData.newPlainText("text", textToCopy);
                // 将 ClipData 对象放入剪贴板
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
                // 关闭 PopupWindow
                popupWindow.dismiss();
            }
        });

        // 计算文本的位置
        int[] location = new int[2];
        anchorView.getLocationInWindow(location);
        int x = location[0];
        int y = location[1] + anchorView.getHeight();

        // 显示 PopupWindow
        popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY, x, y);
    }

    /**
     * 网络异常
     */
    public static boolean invokeHttpError(Activity activity, Object e) {
        if (activity.isFinishing() || activity.isDestroyed()) {
            return false;
        }
        if (e != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    // telnet 百度 80
                    boolean testConnected = telnet("www.baidu.com", 80, 200);
                    if (testConnected) {
                        // telnet 主服务器
                        boolean mainConnected = telnet(getIp(), 1221, 200);
                        if (mainConnected) {
                            DialogUtils.show(activity,"网络异常,连接超时");
                        } else {
                            DialogUtils.show(activity,"网络异常,连接超时");
                        }
                    } else {
                        DialogUtils.show(activity,"网络异常,连接超时");
                        //SystemUtils.showAlertDialog(activity, "网络异常,连接超时", "");
                    }
                    Looper.loop();
                }
            }).start();
        }
        return false;
    }
    /**
     * telnet端口,Android中此段代码不能放在主线程中执行
     */
    public static boolean telnet(String ip, int port, int timeout) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ip, port), timeout);
            return socket.isConnected();
        } catch (Exception e) {
            System.out.println("telnet " + ip + ";" + port + " exception;" + e.getMessage());
        }
        return false;
    }
    /**
     * 获取当前域名
     */
    public static String getIp() {
        if (Data.isNotNull(RetrofitUtil.HOST_URL)) return "124.221.243.113";
        else return "";
    }



    /**
     * 调用系统拍照
     * @param activity activity
     * @param requestCode 请求码
     * @return 返回文件保存的路径
     */
    public static String takePhotos(Activity activity, int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //生成唯一文件名
        SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String filename = timeStampFormat.format(new Date()) + ".jpg";
        //生成拍照路径
        String filePath = photoDir + filename;
        File file = new File(photoDir + filename);
        Uri photoUri = installApk(activity, filePath);
        //将文件(file)转换为一个URI
       // Uri photoUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".provider", file);
        // 拍照完不进入预览模式，直接返回结果
        intent.putExtra("android.intent.extra.quickCapture", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        //回调结果
        activity.startActivityForResult(intent, requestCode);
        return filePath;
    }

    /**
     * 获取版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 从服务器上获取文件
     */
    public static File getFileFromServer(String path, String lastVersion,ProgressDialog pd,Activity activity) throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
            pd.setMax(conn.getContentLength());
            // pd.setMax(100);
            InputStream is = conn.getInputStream();
            //如果报错缓存activity.getExternalFilesDir(null)是否解决？
            // File file = new File(activity.getExternalFilesDir(null), "warehouse"+lastVersion+".apk");
            File file = new File(Environment.getExternalStorageDirectory(), "warehouse"+lastVersion+".apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                // 获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
     * 安装APK
     */
    public static void installApk(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static  Uri installApk(Context context, String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        Uri apkUri = null;
        //L.i("安装路径=="+downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //这句很重要
            apkUri = FileProvider.getUriForFile(Objects.requireNonNull(context), BuildConfig.APPLICATION_ID + ".fileProvider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }

        context.startActivity(intent);
        return  apkUri;
    }

    /**
     * 字符串为空判断
     * @param str 字符串
     * @return boolean
     */
    public static boolean isEmpty(String str) {
        return str == null || str.equals("") || str.equals("null");
    }

    public static void glideLoad(Activity activity, String url, ImageView imageView, int defaultImage) {
        if (activity != null && !activity.isDestroyed() && !activity.isFinishing()) {
            Glide.with(activity)
                    .load(url)
                    .error(defaultImage)  // 加载失败显示
                    .crossFade()    // 过度动画
                    .signature(new StringSignature(photoCacheTime)) // 缓存图片过期时间
                    .into(imageView);
        } else {
            Log.i(TAG, "Picture loading failed,context is null");
        }
    }

    /**
     * 展示警示框
     */
    public static void showAlertDialog(Context context, String title, String msg, DialogInterface.OnClickListener listener) {
        if (isContextExisted(context)) {
            AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title).setMessage(msg).setPositiveButton("确认", listener).show();
            dialog.setCancelable(false);    // 不可取消
        }
    }

    public static void showAlertDialog(Context context, String title, String msg) {
        if (isContextExisted(context)) {
            try {
                alertDialog = new AlertDialog.Builder(context).setTitle(title).setMessage(msg)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
                // 设置按钮字体大小
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(24);
                // 设置标题字体
                Field mAlert = null;
                mAlert = AlertDialog.class.getDeclaredField("mAlert");
                mAlert.setAccessible(true);
                Object Controller = mAlert.get(alertDialog);
                //修改message信息
                Field mMessage = Controller.getClass().getDeclaredField("mMessageView");
                mMessage.setAccessible(true);
                TextView mMessageView = (TextView) mMessage.get(Controller);
                mMessageView.setPadding(20, 5, 5, 5);
                //title样式修改成色
                Field mTitle = Controller.getClass().getDeclaredField("mTitleView");
                mTitle.setAccessible(true);
                TextView mTitleView = (TextView) mTitle.get(Controller);
                if (mTitleView != null) {
                    mTitleView.setTextSize(24); // 标题
                    mMessageView.setTextSize(20);   // 文本
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断context是否存活
     */
    public static boolean isContextExisted(Context context) {
        if (context != null) {
            if (context instanceof Activity) {
                return !((Activity) context).isFinishing() && !((Activity) context).isDestroyed();
            } else return context instanceof Application;
        }
        return false;
    }

    /**
     * 根据手机的分辨率从dp的单位转成为px(像素)
     * @param context 上下文
     * @param dpValue dp值
     * @return px(像素)
     */
    public static int dipToPx(Context context,float dpValue){
        //获取当前手机的像素密度
        final float scale = context.getResources().getDisplayMetrics().density;
        return  Math.round(dpValue*scale);//四舍五入取整
    }

    /**
     * 根据手机的分辨率从px(像素)的单位转成为dp
     * @param context 上下文
     * @param pxValue px(像素)
     * @return dp
     */
    public static int pxToDip(Context context,float pxValue){
        //获取当前手机的像素密度
        final float scale = context.getResources().getDisplayMetrics().density;
        return Math.round(pxValue/scale);//四舍五入取整
    }

    /**
     * 获取屏幕的宽度
     * @param ctx 上下文
     * @return 屏幕的宽度
     */
    public static int getScreenWidth(Context ctx){
        //从系统服务中获取窗口管理器
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        //从默认的显示器中获取显示参数保存到dm对象中
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;//返回屏幕的宽度数值
    }

    /**
     * 获取屏幕的高度
     * @param ctx 上下文
     * @return 屏幕的高度
     */
    public static int getScreenHeight(Context ctx){
        //从系统服务中获取窗口管理器
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        //从默认的显示器中获取显示参数保存到dm对象中
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;//返回屏幕的高度数值
    }

    /**
     * 获取屏幕的像素密度
     * @param ctx 上下文
     * @return 屏幕的像素密度
     */
    public static float getScreenDensity(Context ctx){
        //从系统服务中获取窗口管理器
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        //从默认的显示器中获取显示参数保存到dm对象中
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.density;//返回屏幕的像素密度数值
    }

}
